﻿using DotNetty.Codecs.Http;
using iTool.Common;
using iTool.PluginCore.Connector;
using iTool.Utils;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace iTool.Core
{
    public class TestCallConnector
    {
        private static ManagerPluginCoreConnector pluginsManager;

        static TestCallConnector()
        {
            IServiceCollection httpWorkerServices = iBox.GetServiceCollection("HttpWorker");

            var framework = "appsetting.json";
            // 环境变量
            var builder = new ConfigurationBuilder().AddJsonFile(framework, true, true);
            IConfiguration configuration = builder.Build();

            httpWorkerServices.AddSingleton(configuration);

            pluginsManager = new ManagerPluginCoreConnector();
        }

        public static async Task<iToolHttpContext> InvokeAsync(string path, string queryString, string mothodType)
        {
            iToolHttpContext request = new iToolHttpContext();
            request.Path = path;
            request.QueryString = queryString;
            request.Method = new DotNetty.Codecs.Http.HttpMethod(mothodType.ToUpper());

            var worker = await pluginsManager.GetApiWorkerAsync(request);

            if (worker != default)
            {
                Dictionary<string, string> parameters = new Dictionary<string, string>();

                foreach (var item in worker.parameters)
                {
                    parameters.TryAdd(item.Name, item.Value);
                }

                request.ResponseBody =
                    await iTypeExtension
                    .InvokeMethod(worker.worker.Instance, worker.worker.Method, parameters, t => t == typeof(AbstractHttpContext) ? request : null);
            }
            else
            {
                request.ResponseStatus = HttpResponseStatus.NotFound;
            }

            return request;
        }
    }
}
